(function () {
  new Vue({
    el: '#voucher',
    data() {
      return {
        columns: '#',
        orders: '#',
        page: 1, // 页面
        limit: 10, // 条数
        pageLimits: [10, 15, 20], // 分页条数
        isExtenseFlag: false, //展开收起
        isbill: false, //开账设置
        screeningList: [{
          name: '未导出',
          code: 'N',
          num: '0',
        }, {
          name: '已导出',
          code: 'Y',
          num: '0',
        }], //筛选项
        screeningStatus: [], //筛选状态
        StatuscountData: {},
        isExport: false,
        keyword: '',
        acctVoucherTypes: [], //凭证类型列表
        voucherTypeName: [], //凭证类型
        exportBeginDate: '', //导出开始日期
        exportEndDate: '', //导出结束日期
        beginDate: '',
        endDate: '',
        voucherBeginDate: '', // 凭证开始日期
        voucherEndDate: '', //凭证结束日期
        orderBeginDate: '', //制单开始日期
        orderEndDate: '', //制单结束日期
        contractId: '', //合同id
        intentId: '', //意向id
        projectIds: '', //所有项目Id
        projectId: '', //选中单个项目
        projectList: [], //所有项目
        permissions: JSON.parse(window.localStorage.getItem('permissions')),
        configList: [{
          "id": "1",
          "voucherPeriod": "1",
          "beignDate": "2019-01-02",
          "endDate": '2019-05-26',
          "status": "OPEN",
        }, {
          "id": "2",
          "voucherPeriod": "2",
          "beignDate": "2019-01-02",
          "endDate": '2019-05-26',
          "status": "CLOSED",
        }],
        openYears: ["2019", "2020"],
        selectYear: '',
        showYY_MM: '',
        data: '',
        isScroll: false,
        selectedData: [],
        selectedProject: [],
        selectedBuilding: [],
        selectedFloor: [],
        selectedUnit: [],
        buildingList: [],
        floorList: [],
        unitList: [],
        exportPro: [], //导出项目的id
        flagload: false,

        pushFlag: false,
        pushIds: [],

        editObj: {
          voucherDate: '',
          documentingUserName: '',
        },
        editFlag: false,
      }
    },
    filters: {
      formatUndefined: function (item) {
        if (!item) return '--'
        if (typeof item == 'number') {
          if (!isNaN(item) && item.toString().length == 13) {
            return hlDateUtil.formatUTCDate(item, 'yyyy-MM-dd HH:mm')
          };
        }
        return item
      },
      formatDate: function (time) {
        if (time === undefined) return '--'
        return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd')
      },
    },
    watch: {
      exportBeginDate() {
        this.checkDateB();
      },
      exportEndDate() {
        this.checkDateE();
      },
      selectedData() {
        this.projectId = this.selectedData.join('')
      }
    },
    computed: {
      isAllFlag() {
        let flag = true
        this.data.acctVouchers.map(item => {
          if (this.pushIds.indexOf(item.id) == -1) {
            flag = false
          }
        })
        return flag
      }
    },

    mounted() {
      hlSelectUi(true);
      if (this.permissions.indexOf('c377') > -1) {
        this.screeningList.push({
          name: '未推送',
          code: 'No',
          num: '0',
        }, {
          name: '已推送',
          code: 'Yes',
          num: '0',
        })
      }
      this.getProjectList();
      this.getVoucherTypes();
      this.getBliiDate();

    },

    methods: {
      openSearch: function () {
        if (this.isExtenseFlag == true) {
          this.isExtenseFlag = false;
          return false;
        }
        if (this.isExtenseFlag == false) {
          this.isExtenseFlag = true;
          return false;
        }
      },
      // 作废
      invalidItem(item) {
        let that = this
        hllayer.confirm('此操作不可逆转，确认作废吗？', function () {
          hlhttp.delete({
            url: 'acct/voucher_info?voucher_id=' + item.id,
            data: {
              voucher_id: item.id + ''
            },
            success: res => {
              hl.toast('作废成功')
              that.getVoucherList();
            }
          })
        })
      },
      // 编辑按钮
      editItem(item) {
        console.log(item)
        this.editObj = JSON.parse(JSON.stringify(item))
        this.editObj.voucherDate = hlDateUtil.formatUTCDate(this.editObj.voucherDate, 'yyyy-MM-dd')
        this.editFlag = true
      },
      // 确定保存编辑
      saveEdit() {
        let data = {
          voucher_id: this.editObj.id,
          voucher_date: this.editObj.voucherDate,
          document_user_id: this.editObj.documentingUserId,
          document_user_name: this.editObj.documentingUserName,
        }
        hlhttp.put({
          url: 'acct/voucher_info',
          data: data,
          success: res => {
            hl.toast('编辑成功')
            this.editFlag = false
            this.getVoucherList()
          }
        })
      },


      // 推送按钮
      pushBut() {
        this.selectScreening('No')
        this.pushFlag = true
        this.pushIds = []
      },
      selectPushId(id) {
        let i = this.pushIds.indexOf(id)
        if (i == -1) {
          this.pushIds.push(id)
        } else {
          this.pushIds.splice(i, 1)
        }
      },
      selectAllPushId() {
        if (this.isAllFlag) {
          this.data.acctVouchers.map(item => {
            let i = this.pushIds.indexOf(item.id)
            this.pushIds.splice(i, 1)
          })
        } else {
          this.data.acctVouchers.map(item => {
            if (this.pushIds.indexOf(item.id) == -1) {
              this.pushIds.push(item.id)
            }
          })
        }
      },
      submitPush() {
        if (!this.pushIds.length) {
          hl.toast('请选择推送项')
          return
        }
        hlhttp.post({
          url: 'acct/voucher/_push',
          data: {
            voucher_ids: this.pushIds + ''
          },
          success: res => {
            hl.toast('正在推送中，请稍后')
            this.search()
            this.pushFlag = false
          }
        })
      },



      // 获取楼栋
      getBuildingList() {
        var that = this
        hlhttp.get({
          url: 'project/buildings',
          data: {
            project_id: that.selectedProject.join('')
          },
          success: function (res) {
            res.map(item => {
              item.code = item.buildingId
            })
            that.buildingList = res
            that.floorList = []
            that.unitList = []
            that.selectedBuilding = []
            that.selectedFloor = []
            that.selectedUnit = []
          }
        })
      },
      //获取楼层
      getFloorList() {
        var that = this
        hlhttp.get({
          url: 'building/floors',
          data: {
            project_id: that.selectedProject.join(''),
            building_id: that.selectedBuilding.join('')
          },
          success: function (res) {
            res.map(item => {
              item.name = item.floorName
              item.code = item.floorId
            })
            that.floorList = res
            that.unitList = []
            that.selectedFloor = [],
              that.selectedUnit = []
          }
        })
      },
      //获取单元
      getUnitList() {
        var that = this
        hlhttp.get({
          url: 'floor/units',
          data: {
            project_id: that.selectedProject.join(''),
            building_id: that.selectedBuilding.join(''),
            floor_id: that.selectedFloor.join('')
          },
          success: function (res) {
            res.map(item => {
              item.code = item.unitId
              item.name = item.unitName
            })
            that.unitList = res
            that.selectedUnit = []
          }
        })
      },
      //点击排序
      runkDate(val) {
        this.columns = val
        this.orders = this.orders == "#" ? 'ASC' : (this.orders == 'ASC' ? 'DESC' : 'ASC')
        this.getVoucherList();
      },
      // 获取开账日期
      getBliiDate() {
        var that = this
        hlhttp.get({
          url: 'acct/voucher/open_period',
          success: function (res) {
            that.showYY_MM = res.voucherYear + '.' + res.voucherMonth
          }
        })
      },
      //获取账户下的项目Id
      getProjectList() {
        var that = this
        hlhttp.get({
          url: 'user/projects',
          success: function (res) {
            res = hlArrayUtil.removeRepeat(res, 'projectId')
            let arr = []
            res.map(item => {
              item.name = item.projectName,
                item.code = item.projectId
              arr.push(item.projectId)
            })
            that.projectList = res
            that.projectIds = arr.join(',')
            that.getVoucherList();
          }
        })
      },
      // 获取财务凭证列表
      getVoucherList() {
        var that = this
        let arr1 = []
        let arr2 = []
        this.screeningStatus.map(item => {
          if (item == 'Y') {
            arr1.push(item)
          }
          if (item == 'N') {
            arr1.push(item)
          }
          if (item == 'No') {
            arr2.push('N')
          }
          if (item == 'Yes') {
            arr2.push('Y')
          }
        })

        hlhttp.get({
          url: 'acct/voucher_info/_search',
          data: {
            "keyword": this.keyword || '#',
            "voucher_type_name": this.voucherTypeName.length ? this.voucherTypeName.join('') : '#',
            "voucher_date_begin": this.voucherBeginDate || '#',
            "voucher_date_end": this.voucherEndDate || '#',
            "documenting_date_begin": this.orderBeginDate || '#',
            "documenting_date_end": this.orderEndDate || '#',
            "export_flag": arr1.length ? arr1 + '' : '#',
            "push_flag": arr2.length ? arr2 + '' : '#',
            "project_ids": this.selectedProject.length ? this.selectedProject[0] : (this.projectIds || '#'),
            "contract_id": this.contractId || '#',
            "intent_id": this.intentId || '#',
            'columns': this.columns,
            'orders': this.orders,
            "page": this.page,
            "limit": this.limit
          },
          success: function (res) {
            res.acctVouchers.map(item => {
              item.iSselect = false
            })

            that.data = res
            that.screeningList.map(item => {
              if (item.code == 'N') {
                item.num = res.exportNCount
              }
              if (item.code == 'Y') {
                item.num = res.exportYCount
              }
              if (item.code == 'No') {
                item.num = res.pushNCount
              }
              if (item.code == 'Yes') {
                item.num = res.pushYCount
              }
            })

            $("#page").initPage(res.totalPage, that.page, (n) => {
              if (that.page == n) {
                return
              }
              that.page = n;
              that.getVoucherList();
            });
          }
        })
      },
      // 获取凭证类型列表
      getVoucherTypes() {
        var that = this
        hlhttp.get({
          url: 'acct/voucher_type/_list',
          success: function (res) {
            res.map(item => {
              item.code = item.id
            })
            that.acctVoucherTypes = res
          }
        })
      },
      // 选择凭证类型名称
      selectType(name) {
        this.voucherTypeName = [name]
      },
      handleChange() {

      },
      countEnd(val, num) {
        return hlDateUtil.monthInterval_(val, num)
      },
      countBegin(val, num) {
        return hlDateUtil.monthInterval(val, num)
      },
      // 检查时间是否符合要求（2个月范围，B_time = 开始时间，E_time = 结束时间，local_time = 当前选中时间）
      checkDateB() {
        if (!this.exportEndDate) return
        let B = hlDateUtil.monthInterval_(this.exportEndDate, 2)
        this.endDate = this.exportEndDate
        let B_time = new Date(B).getTime();
        let E_time = new Date(this.exportEndDate).getTime();
        let local_time = new Date(this.exportBeginDate).getTime();
        if (local_time < B_time || local_time > E_time) {
          hl.toast('批量导出制单时间段至多两个自然月')
          this.exportBeginDate = ''
          this.$refs.date_begin._data.currentValue = ''
        }
      },
      checkDateE() {
        if (!this.exportBeginDate) {

          return
        }
        let E = hlDateUtil.monthInterval(this.exportBeginDate, 2)
        let B_time = new Date(this.exportBeginDate).getTime();
        let E_time = new Date(E).getTime();
        let local_time = new Date(this.exportEndDate).getTime();
        if (local_time < B_time || local_time > E_time) {
          hl.toast('批量导出制单时间段至多两个自然月')
          this.exportEndDate = ''
          this.$refs.date_end._data.currentValue = ''
        }
      },

      // 查询
      search() {
        this.getVoucherList()
      },
      // 重置
      reset() {
        this.keyword = ''
        this.voucherBeginDate = ''
        this.voucherEndDate = ''
        this.orderBeginDate = ''
        this.orderEndDate = ''
        this.voucherTypeName = []
        this.columns = '#'
        this.orders = '#'
        this.selectedProject = []
        this.selectedBuilding = []
        this.selectedFloor = []
        this.selectedUnit = []
        this.buildingList = []
        this.floorList = []
        this.unitList = []
        this.getVoucherList()
      },
      // 开账设置按钮
      billSwidthBut() {
        this.isbill = true
        this.getYear();
      },
      // 获取会计年
      getYear() {
        var that = this
        hlhttp.get({
          url: 'acct/voucher/period_open_years',
          success: function (res) {
            that.openYears = res
            if (!that.selectYear) {
              that.selectYear = res[0]
            }
            that.getConfig()
          }
        })
      },
      //选择会计年
      setYear(val) {
        this.selectYear = val
        this.getConfig()
      },
      // 凭证开关账配置列表
      getConfig() {
        var that = this
        hlhttp.get({
          url: 'acct/voucher/period_open_config',
          data: {
            year: this.selectYear
          },
          success: (data) => {
            that.configList = data
            data.some(item => {
              if (item.status == 'OPEN') {
                this.showYY_MM = hlDateUtil.formatUTCDate(item.beginDate, 'yyyy.MM')
              }
            })
          }
        })
      },
      // 停用/开启凭证开关账配置
      switchFunc(item) {
        let status = item.status == 'OPEN' ? 'N' : 'Y'
        var that = this
        hlhttp.put({
          url: 'acct/voucher/period_open_config/_status',
          data: {
            id: item.id,
            opt: status
          },
          success: (data) => {
            that.getConfig()
            that.getYear();
          }
        })
      },
      // 选中项目
      selectPro(id) {
        this.projectId = id
      },
      // 生成凭证
      createVoucher() {
        if (!this.projectId) {
          hl.toast('请选择项目')
          return
        }
        let year = this.showYY_MM.split('.')[0]
        let month = this.showYY_MM.split('.')[1]
        var that = this
        hllayer.confirm1('<div>如果当前开账月已有凭证生成，会删除已有凭证，已推送的凭证需在财务软件中删除</div>', function () {
          hlhttp.post({
            url: 'acct/vouchers',
            data: {
              project_id: that.projectId,
              voucher_year: year,
              voucher_month: month,
            },
            success: (data) => {
              that.getVoucherResult()
            },
          })
        })
      },
      //生成凭证结果
      getVoucherResult() {
        let year = this.showYY_MM.split('.')[0]
        let month = this.showYY_MM.split('.')[1]
        var that = this
        this.flagload = true
        hlhttp.get({
          url: 'acct/voucher_result',
          data: {
            project_id: this.projectId,
            voucher_year: year,
            voucher_month: month,
          },
          success: (data) => {
            if (data.result == 'Y') {
              that.flagload = false
              that.getVoucherList()
            } else {
              setTimeout(() => {
                that.getVoucherResult()
              }, 1000)
            }
          },
          error: function () {
            that.flagload = false
          }
        })
      },
      // 导出凭证
      exportFunc() {
        if (!this.exportBeginDate || !this.exportEndDate) {
          hl.toast('请选择制单日期')
          return
        }
        if (!this.exportPro.length) {
          hl.toast('请选择项目')
          return
        }
        var that = this
        hlhttp.get({
          baseUrl: exclUrl,
          url: 'resource/acct/voucher/_export',
          data: {
            begin_date: this.exportBeginDate,
            end_date: this.exportEndDate,
            project_id: this.exportPro.join(''),
          },
          success: (data) => {
            hl.toast('导出成功')
            that.getVoucherList();
            window.open(data.excel_url)
          }
        })
      },
      // 重置筛选状态
      resetStatus() {
        if (this.pushFlag) return
        this.screeningStatus = []
        this.page = 1
        this.getVoucherList();
      },
      // 筛选
      selectScreening(code) {
        if (this.pushFlag) return
        this.screeningStatus = [code]
        this.page = 1
        this.getVoucherList();
      },
      // 去详情
      goTodetail(item) {
        hlUrlUtil.goTo('voucherDetail', {
          'ddtab': true,
          'id': item.id,
          'date': item.documentingDate
        }, true)
      },
      // 导出按钮
      exportBut() {
        this.isExport = true
        this.exportEndDate = ''
        this.exportBeginDate = ''
      },
      // 设置分页数量
      setMoreNum(n) {
        this.limit = n;
        this.getVoucherList()
      },
      showScroll() {
        this.isScroll = true;
      },
      hideScroll() {
        this.isScroll = false;
      }
    },
  })
}())